package cn.core.tool.aspect;

import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * Mapper AOP 拦截器 >>> 批量保存
 */
@Log4j2
@Aspect
@Component
@ConditionalOnProperty(prefix = "proconf", name = "mapper-aspect-save-batch", havingValue = "true")
public class MapperAspectSaveBatch {

  @Pointcut("execution(public * cn.core..mapper..*.saveBatch(..))")
  public void saveBatch() {
  }

  @SuppressWarnings("Duplicates")
  @Before("saveBatch()")
  public void doBefore(JoinPoint joinPoint) throws Exception {
    try {
      for (Object o : joinPoint.getArgs()) {
        if (o != null) {
          if (o instanceof Collection) {
            for (Object eo : (Collection<?>) o) {
              if (eo != null) {
                try {
                  eo.getClass().getMethod("setVersions", Long.class).invoke(eo, 1l);
                } catch (NoSuchMethodException e) {
                }
              }
            }
          }
        }
      }
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

}
